package collaborynth.apod;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

public class ApodActivity extends Activity {
    /** Called when the activity is first created. */

    private static final String LOG_TAG = "ImageDownloader";
    
    ImageView imView;
    String imageUrl;
    RSSHandler rsshandler;
    List<RSSObject> rssobjects;
    List<Bitmap> imgs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imView = (ImageView)findViewById(R.id.imageView1);
        imgs = new ArrayList<Bitmap>();
        new DownloadRSSTask().execute("http://apod.nasa.gov/apod.rss");
        while(rssobjects == null){
        	
        }
        try {
			startDisplay();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public void startDisplay() throws InterruptedException{
    	Bitmap bm;
    	Log.d("SLIDESHOW", "start display");
    	for(int i = 0; i < rssobjects.size(); i++){
    		RSSObject robj = rssobjects.get(i);
    		robj.getImage();
    		try{
    			imView.setImageBitmap(robj.bm);
    			Log.d("IVIEW", Integer.toString(imView.getVisibility()));
    		}catch (Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    
    private class DownloadRSSTask extends AsyncTask<String, Void, String> {
    	RSSHandler rssh;
        protected String doInBackground	(String... urls) {
        	getRSS(urls[0]);
        	return null;
        }
        
        String getRSS(String url){
        	rssh = new RSSHandler();
        	rssobjects = rssh.getResults(url);
        	return null;
        }
        
        protected void onPostExecute(String result) {
        	/*try {
				//startDisplay();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
        }
    }
}